<?php


namespace app\common\utils;


use Firebase\JWT\JWT;
use TencentCloud\Common\CommonClient;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Vod\V20180717\Models\DescribeMediaInfosRequest;
use TencentCloud\Vod\V20180717\VodClient;
use think\facade\Log;

class TcUpload
{
    protected static $key = 'TxtyhLlgo7J3iOADIron';
    
    protected static $appid = 1500029905;
    
    
    
    /**
     * @param int $expire_time 秒
     * @return array
     * Created by chenyawei on 2024/8/14
     * Description:
     */
    public static function getSign($expire_time = 86400)
    {
        $secret_id = env('Tencent.file_upload_id');
        $secret_key = env('Tencent.file_upload_key');
        // 确定签名的当前时间和失效时间
        $current = time();
        $expired = $current + $expire_time;  // 签名有效期：1天
        // 向参数列表填入参数
        $arg_list = [
            "vodSubAppId"=>self::$appid,
            "secretId" => $secret_id,
            "currentTimeStamp" => $current,
            "expireTime" => $expired,
            "random" => time().rand(),
            "procedure"=>"极速高清", // 任务流名称
        ];
        // 计算签名
        $original = http_build_query($arg_list);
        $signature = base64_encode(hash_hmac('SHA1', $original, $secret_key, true) . $original);
        return compact('signature', 'expired');
    }


    public static function getPlaySign($fileId)
    {
        if (!$fileId) return false;
        $audioVideoType = "RawAdaptive"; // 播放的音视频类型
        $rawAdaptiveDefinition = 10; // 允许输出的未加密的自适应码流模板 ID
        $imageSpriteDefinition = 10; // 进度条预览的雪碧图模板 ID
        $currentTime = time();
        $psignExpire = $currentTime + 3600 * 3; // 可任意设置过期时间 3小时
        $urlTimeExpire = dechex($psignExpire); // 可任意设置过期时间，16进制字符串形式


        $payload = array(
            "appId" => self::$appid,
            "fileId" => $fileId,
            "contentInfo" => array(
                "audioVideoType" => $audioVideoType,
                "rawAdaptiveDefinition" => $rawAdaptiveDefinition,
                "imageSpriteDefinition" => $imageSpriteDefinition
            ),
            "currentTimeStamp" => $currentTime,
            "expireTimeStamp" => $psignExpire,
            "urlAccessInfo" => array(
                "t" => $urlTimeExpire
            )
        );
        return  JWT::encode($payload, self::$key, "HS256");
    }
    
    public static function getTranscode(){
        $secret_id = env('Tencent.file_upload_id');
        $secret_key = env('Tencent.file_upload_key');
        try {
            $cred = new Credential($secret_id, $secret_key);
            
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("vod.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new CommonClient("vod", "2018-07-17", $cred, "", $clientProfile);
            $params = [ "SubAppId"=>self::$appid];
            $res =  $client->callJson("PullEvents", $params);
            Log::info('视频处理相应结果:'.json_encode($res));
            if(isset($res['EventSet'])){
                return $res['EventSet'];
            }
            return [];
        }
        catch(TencentCloudSDKException $e) {
            Log::info('获取视频处理结果失败:'. $e->getMessage());
            return [];

        }
    }

    /**
     * Created by chenyawei on 2024/8/18
     * Description:通知腾讯, 处理完成
     * 
     */
    public static function notifyTc($params){
        if(empty($params))return false;
        $secret_id = env('Tencent.file_upload_id');
        $secret_key = env('Tencent.file_upload_key');
        try {
            $cred = new Credential($secret_id, $secret_key);

            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("vod.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new CommonClient("vod", "2018-07-17", $cred, "", $clientProfile);
            $baseParams =  [ "SubAppId"=>self::$appid];
            $params = array_merge($baseParams, $params);
            $res =  $client->callJson("ConfirmEvents", $params);
            Log::info('视频处理确认:'.json_encode($res));
            return $res;
        }
        catch(TencentCloudSDKException $e) {
            Log::info('视频处理确认失败信息:'. $e->getMessage());
            return false;

        }
    }

    /**
     * @param $fileIdArr
     * @return bool|mixed
     * Created by chenyawei on 2024/9/3
     * Description:单次最多20个fileid 
     */
    public static function getVideoAndAudioUrl($fileIdArr){
        if(empty($fileIdArr))return [];
        $fileIdArr = array_unique($fileIdArr);
        if(count($fileIdArr) >100)return [];
        $secret_id = env('Tencent.file_upload_id');
        $secret_key = env('Tencent.file_upload_key');
        try {
            $cred = new Credential($secret_id, $secret_key);

            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("vod.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new CommonClient("vod", "2018-07-17", $cred, "", $clientProfile);
            $params["SubAppId"] =  self::$appid;
            $params['FileIds'] =  $fileIdArr;
//            $params['Filters'] =  ['basicInfo'];
            $params['Filters'] =  ['transcodeInfo'];
            $res =  $client->callJson("DescribeMediaInfos", $params);
            // 输出json格式的字符串回包
            Log::info('获取资源路径结果:'.json_encode($res));
            return isset($res['MediaInfoSet']) ?$res['MediaInfoSet'] :[];
        }
        catch(TencentCloudSDKException $e) {
            Log::info('获取资源路径结果失败信息:'. $e->getMessage());
            return [];
        }
    }
}